package cn.huas.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtil {
	static  private String username;
	static  private String password;
	static  private String url;

  public static Connection createConn(){
	  
	  Connection conn=null;
	  try {
		  DBUtil db= new DBUtil();
		  InputStream inputStream = db.getClass().getClassLoader().getResourceAsStream("jdbc.properties");    
		  Properties p = new Properties();    
		  try {    
		   p.load(inputStream); 
		   url=p.getProperty("jdbc.url");
		   username=p.getProperty("jdbc.username");
		   password=p.getProperty("jdbc.password");
		   inputStream.close();
		  } catch (IOException e1) {   
		   e1.printStackTrace();    
		  }  
		  Class.forName("com.mysql.jdbc.Driver");
		  conn=DriverManager.getConnection(url,username,password);
	} catch (SQLException e) {
		e.printStackTrace();
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
	}
	  
	  return conn;
  }
  public static PreparedStatement prepare(Connection conn,String sql){
	  PreparedStatement ps = null;
	  try {
		ps=conn.prepareStatement(sql);
	} catch (SQLException e) {
		e.printStackTrace();
	}
	  return ps;
  }
  public static void close(Connection conn){
	  try {
		if(conn!=null)
		conn.close();
		conn=null;
	} catch (SQLException e) {
		e.printStackTrace();
	}
  }
  public static void close(PreparedStatement ps){
	  try {
		if(ps!=null)
		ps.close();
		ps=null;
	} catch (SQLException e) {
		e.printStackTrace();
	}
  }
  public static void close(ResultSet rs){
	  try {
		if(rs!=null){
			rs.close();
			rs=null;
		}
	} catch (SQLException e) {
		e.printStackTrace();
	}
  }
  public static void close(InputStream in){
	  try {
		if(in!=null)
			in.close();
		in=null;
	} catch (Exception e) {
		e.printStackTrace();
	}
  }
}
